﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.Jobs;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.JobsHandlers
{
    public class JobTreeListHandlers : IRequestHandler<JobTreeListCommand, List<PublicTree<Job>>>
    {
        private readonly IjobRep ijobRep;

        public JobTreeListHandlers(IjobRep ijobRep)
        {
            this.ijobRep = ijobRep;
        }

        public async Task<List<PublicTree<Job>>> Handle(JobTreeListCommand request, CancellationToken cancellationToken)
        {
            var list = await ijobRep.GetvaluesByResult(x => x.Jpid == request.pid);
            var treelist = new List<PublicTree<Job>>();
            foreach (var item in list.ToArray())
            {
                var tree = new PublicTree<Job>
                {
                    children = null,
                    label = item.Jname,
                    level = item.Jid,
                    route = null,
                };
                treelist.Add(tree);
                await Getchidren(item.Jid, tree);
            }
            return treelist;
        }
        public async Task Getchidren(int id, PublicTree<Job> tree)
        {
            var list = await ijobRep.GetvaluesByResult(x => x.Jpid == id && !x.IsDel);
            foreach (var item in list)
            {
                if (tree.children == null)
                {
                    tree.children = new List<PublicTree<Job>>();
                }
                var substree = new PublicTree<Job>
                {
                    label = item.Jname,
                    level = item.Jid,
                    route = null,
                    children = null
                };
                tree.children.Add(substree);
                await Getchidren(item.Jid, substree);
            }
        }
    }
}
